<template>
	<view class="content">
		<view v-if="stage==0" style="margin: 60rpx 20rpx;">
			<view style="margin: 10rpx">
				输入当前用户学分
				<u--input type="number" placeholder="请输入当前用户学分" border="surround" v-model="point"></u--input>
				输入市民通Code
				<u--textarea v-model="code" placeholder="在此输入市民通code" ></u--textarea>
				或输入市民通Token
				<u--textarea v-model="token" placeholder="在此输入市民通token" maxlength="1000"></u--textarea>
				<text @tap="onclickText()" style="word-break: break-all;color: $u-primary;font-size: 20rpx;" :selectable="true">{{notice}}</text>
			</view>
			<u-button style="margin: 20rpx 0;" type="primary" text="点击跳转兑换页" @click="sending?'':loginAndJump()"></u-button>
			<u-button type="primary" text="清空缓存" @click="clear()"></u-button>
			
		</view>
		<view v-if="stage==1" style="margin: 60rpx 20rpx;">
			<view style="display: flex;margin: 10rpx">
				<view style="font-size: 50rpx;margin-left:220rpx;">
					积分兑福利
				</view>
				<view style="margin-left:50rpx;margin-top: 10rpx;" @tap="showNotice?showNotice=false:showNotice=true">
					兑换规则
				</view>				
			</view>
			<view v-if="showNotice" style="color: #666;font-size: 24rpx;margin: 10rpx 20rpx;" @tap="showNotice?showNotice=false:showNotice=true">
				您通过学习累计获得的积分可以兑换为心加商城积分，可用于兑换心加商城福利。积分兑换不消耗学分.
			</view>	
			<view style="display: flex;justify-content: space-between;margin: 50rpx 120rpx;">
				<view>
					<view style="text-align: center;">
						{{memberInfo.currentPointInfo.point}}积分
					</view>
					<view>
						兑换可用
					</view>	
				</view>
				<view>
					<view style="text-align: center;">
						{{point}}学分
					</view>
					<view>
						累计获得
					</view>	
				</view>				
			</view>
			<view style="display: flex;justify-content:center;margin: 20rpx">
				<view style="display: flex;">
					<view style="margin-top: 15rpx;margin-right: 20rpx;">
						花
					</view>	
					<view style="width: 100rpx;">
						<u--input type="number" placeholder="积分" border="surround" v-model="currentPoint"></u--input>
					</view>	
					<view style="margin-top: 15rpx;">
						积分
					</view>	
				</view>	
			</view>	
			<view style="display: flex;justify-content: space-between;margin: 0rpx 50rpx">
				<view>
					0%
				</view>	
				<view>
					25%
				</view>
				<view>
					50%
				</view>
				<view>
					100%
				</view>
			</view>
			<u-slider v-model="sliderValue" min="0" max="100" step="5" @changing="sliderChanging()"></u-slider>
			<view style="text-align: center;margin: 20rpx;">
				可兑换{{targetPonit}}心加商城积分
			</view>
			<u-button style="margin: 20rpx 0;" type="primary" text="兑换心加商城积分" @click="isWechatPage?'':exchangePoint()"></u-button>
			
			<!-- <u-button type="primary" text="清空缓存" @click="isWechatPage?'':clear();stage=0"></u-button> -->
			<u-overlay :show="isWechatPage" opacity="0.6" >
				<view @click="clear();stage=0" style="margin: 100rpx 100rpx;margin-top: 500rpx;color: #FFF;text-align: center;">请点击下方按钮德阳市民通微信小程序中进行积分兑换！</view>
				<view v-if="isWechatPage" style="display: flex;justify-content:center">
					<wx-open-launch-weapp id="launch-btn" username="gh_eef45066c07d" path="pages/webview/webview.html?url=https%3A%2F%2Fthird.dysmt.cn%2Fthird%2Fcitizen-auth%2Fthird-mini-auth.html%3Fmpt%3Dempty%26rUrl%3Dhttps%3A%2F%2Fjy.dycic.net">
						<script type="text/wxtag-template">	
							<style>
								.btn {								
									border-radius: 5px;  
									margin-top: 20px;
									height: 30px;  
									font-size: 18px; 
									margin: 0 0px;
									padding:0 10px;
									border: none !important;  
									color: #FFF;  
									background:#007aff;
								}
							</style>
								<button class="btn" type="default">
									跳转积分兑换页			
								</button>  
						</script>
					</wx-open-launch-weapp>
				</view>
			</u-overlay>		
		</view>
		<view v-if="stage==2" style="margin: 60rpx 20rpx;">	
			<view style="margin: 30rpx">
				<view style="font-size: 50rpx;display: flex;justify-content:center;margin:20rpx">
					兑换成功
				</view>
				<view style="font-size: 30rpx;display: flex;justify-content:center">
					您花费{{currentPoint}}积分兑换了{{targetPonit}}心加商城积分
				</view>
			</view>
			<!-- <u-button style="margin: 10rpx" type="primary" text="清空缓存" @click="clear();stage=0"></u-button> -->
			<u-button style="margin: 10rpx" type="primary" text="返回兑换" @click="stage=1"></u-button>
			<view style="display: flex;justify-content: center;margin-top: 30rpx;">扫一扫，去心加商城领福利</view>
			<view style="display: flex;justify-content: center;margin-top: 30rpx;">	
				<image mode="aspectFill" style="width: 300rpx;height: 300rpx;" src="../../static/qr.png"></image>
			</view>
			
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database() 
	export default {
		data() {
			return {
				isSmt:false,
				isWechatPage:false,
				currentPoint:0,
				targetPonit:0,
				memberInfo:{
					currentPointInfo:{
						point:null
					}
				},
				showNotice:false,
				sliderValue: 50,
				point:50,
				sending:false,
				stage: 0,
				notice:"在上面输入框中输入市民通code,可通过 https://auths.dysmt.cn/oauth/authorize?client_id=72398458411686443043313906063157&response_type=code&grant_type=authorization_code&scope=snsapi_userinfo&redirect_uri=https://jy.dycic.net(点击复制) 登陆后获取,输入并确认后,将获取市民通token及手机号用于登录及积分页面操作",
				code:"",
				token:""
			}
		},
		onLoad() {
			this.initWechat()
			let ua = window.navigator.userAgent.toLowerCase();
			this.getUrlParam()
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				if (ua.match(/miniProgram/i) == 'miniprogram') {
					//此处在微信小程序webview中，拉起单点登录
				}
				else{
					//此处提供微信网页跳转微信小程序方法
					// this.initWechat()
					this.isWechatPage = true
				}
			}			
			if(uni.getStorageSync('userInfo')){//缓存有token则检测是否有效,有效自动跳转兑换页
				// this.smtAuth()//正式环境打开
			}
			if(cst.isCstoon()){
				this.isSmt = true		
			}
		},
		methods: {
			onclickText(){//复制网址
				uni.setClipboardData({
					data:"https://auths.dysmt.cn/oauth/authorize?client_id=72398458411686443043313906063157&response_type=code&grant_type=authorization_code&scope=snsapi_userinfo&redirect_uri=https://jy.dycic.net",
					showToast:true
				});
			},
			getUrlParam() {//页面载入时调用
			//可以以http://XXXX.XXXX.cc/?smtId=24c343bacb714fb58eda85c7fad1cf3d&phone=1851XXXX55&point=120&token=ey.....#/
			//的形式直接传入手机号、积分、市民通id、token信息
				var reg = new RegExp("(^|&)" + "token" + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
				var r = window.location.search.substr(1).match(reg); //匹配目标参数
				 if (r == null){
						this.stage = 0
					}
				else{	
					uni.setStorageSync("userInfo",{
						"smtId":location.search.substr(1).match(new RegExp("(^|&)" + "smtId" + "=([^&]*)(&|$)"))[2],
						"phone":location.search.substr(1).match(new RegExp("(^|&)" + "phone" + "=([^&]*)(&|$)"))[2],
						"token":location.search.substr(1).match(new RegExp("(^|&)" + "token" + "=([^&]*)(&|$)"))[2]
					})					
					// this.smtAuth()
					this.loadMemberInfo()//测试时打开，正式的不要
					this.point = location.search.substr(1).match(new RegExp("(^|&)" + "point" + "=([^&]*)(&|$)"))[2]
					this.stage = 1	
				}
			},
			sliderChanging(){				
				this.currentPoint = Math.floor(this.memberInfo.currentPointInfo.point * this.sliderValue / 100)
				this.targetPonit = Math.floor(this.currentPoint * this.memberInfo.detailRule.ratioInput / this.memberInfo.detailRule.ratioOutput)
			},
			clear(){
				uni.clearStorage();
			},
			async smtAuth(){
				uni.request({
				    url: 'https://authr.dysmt.cn/resource/user/userinfo?access_token='+uni.getStorageSync('userInfo').token, 
				    data:{},
					method:"POST",
				    success: (res) => {						
						if(res.data.status == 1){
							console.log('token有效')
							this.loadMemberInfo()
							this.stage = 1
							
						}else{
							console.log('token无效或已过期')
							uni.showToast({
								title:"请输入code"
							})
						}
				    }
				});
			},
			async loadMemberInfo(callback){
				const res = await uniCloud.callFunction({
					name: 'cityMiddleGround',
					data: {
						action: 'http/memberInfo',
						data: {
							// "smtId":uni.getStorageSync('userInfo').smtId							
							"smtId":"00002eccc8b14c22a6c9fcd83a1392b8",//测试ID uni.getStorageSync('userInfo').smtId
						}
					}
				})
				if(res.success){
					this.memberInfo = res.result.data
					this.currentPoint = Math.floor(this.memberInfo.currentPointInfo.point * this.sliderValue / 100)
					this.targetPonit = Math.floor(this.currentPoint * this.memberInfo.detailRule.ratioInput / this.memberInfo.detailRule.ratioOutput)
					console.log('memberInfo',res.result.data)	
					callback && callback()//如果回调函数存在，则执行该回调函数
				}
			},
			async exchangePoint(callback){
				if(this.currentPoint == 0){
					uni.showToast({
						title:"兑换积分不能为0"
					})
				}else{
					const res = await uniCloud.callFunction({
						name: 'cityMiddleGround',
						data: {
							action: 'http/pointExchange',
							data: {
								// "smtId":uni.getStorageSync('userInfo').smtId,
								"smtId":"00002eccc8b14c22a6c9fcd83a1392b8",//测试ID uni.getStorageSync('userInfo').smtId
								"num":this.currentPoint,
								"token":uni.getStorageSync('userInfo').token
							}
						}
					})
					if(res.success){
						console.log('pointExchangeInfo',res.result.data)	
						uni.showToast({
							title:"兑换成功"
						})
						this.loadMemberInfo(()=>{
							this.stage = 2
						})
						callback && callback()//如果回调函数存在，则执行该回调函数
					}
				}
			},
			async loginAndJump(){
				if(this.code){
					this.sending = true
					//下面是云函数,实际开发时替换为uni.request调接口即可
					const res = await uniCloud.callFunction({
						name: 'cityMiddleGround',
						data: {
							action: 'http/smtUserInfo',
							data: {
								"code":this.code
							}
						}
					})
					if(res.success){
						this.sending = false
						console.log('userInfo',res.result)	
						uni.setStorageSync('userInfo',res.result)
						this.loadMemberInfo(()=>{
							this.stage = 1
						}) 
					}
				}
				else if(!this.code&&this.token){
					uni.request({
					    url: 'https://authr.dysmt.cn/resource/user/userinfo?access_token='+this.token, 
					    data:{},
						method:"POST",
					    success: (res) => {						
							if(res.data.status == 1){
								console.log('token有效',res.data)
								uni.setStorageSync('userInfo',{
									"smtId":res.data.content.id,
									"phone":res.data.content.phone,
									"token":res.data.content.userToken
								})
								this.loadMemberInfo()
								this.stage = 1
							}else{
								console.log('token无效或已过期')
								uni.showToast({
									title:"请输入code"
								})
							}
					    }
					});
				}
				else{
					uni.showToast({
						title:"请输入code"
					})
				}
				
			},
			async initWechat(){
				//这是演示用在中转效果上，若当前在微信公众号H5中，跳转小程序
				//jsapi_ticket 在【已认证】的微信公众号基本配置中获取AppID AppSecret，设置ip白名单，先拿access_token再拿jsapi_ticket，需要配合定时任务，见云函数wxofficialacconut
				const res = await uniCloud.callFunction({
					name: 'cityMiddleGround',
					data: {
						action: 'http/getticket',
						data: {}
					}
				})
				//url：设置与开发-公众号设置-功能设置-JS接口安全域名
				this.initdata = 'jsapi_ticket='+res.result.data[0].currentJsapiTicket+'&noncestr=MaRTl0HFsMhdAfCM&timestamp='+Math.round(new Date().getTime()/1000).toString()+'&url='+window.location.href//.split('#')[0]
				console.log("initdata::",this.$dataSha1(this.initdata),this.initdata)
				let _this = this
				jWeixin.config({
				  debug: false, 
				  appId: 'wx23b5dafd4b8cca6d', // 必填，公众号的唯一标识
				  timestamp: Math.round(new Date().getTime()/1000).toString(), // 必填，生成签名的时间戳
				  nonceStr: 'MaRTl0HFsMhdAfCM', // 必填，生成签名的随机串
				  signature: _this.$dataSha1(_this.initdata),// 必填，签名
				  jsApiList: ['updateAppMessageShareData','updateTimelineShareData','wx-open-launch-weapp'],// 必填，需要使用的JS接口列表
				  openTagList: ['wx-open-launch-weapp']
				});
				jWeixin.ready(function(){
					jWeixin.checkJsApi({
					  jsApiList: ['checkJsApi','updateAppMessageShareData','updateTimelineShareData'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
					  success: function(res) {
					  // 以键值对的形式返回，可用的api值true，不可用为false
						console.log('checkJsApi:', res)
					  }
					});
					  jWeixin.updateAppMessageShareData({
						title: 'demo...',
						desc: "demo...", // 分享描述
						link: "http://h5.bashe.cc", // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
						imgUrl: "http://h5.bashe.cc/b.jpg", // 分享图标
						success: function () {
						  // 设置成功
						}
					  });
					  jWeixin.updateTimelineShareData({
						title: 'demo...',
						link: "http://h5.bashe.cc",  // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
						imgUrl: "http://h5.bashe.cc/b.jpg", // 分享图标
						success: function () {
						  // 设置成功
						}
					});
				});
				// });
			},
		}
	}
</script>

<style>

</style>
